package com.fafa.swing.base;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author : fafa
 * @version V1.0
 * @Project: SwingTest
 * @Package com.fafa.swing
 * @Description: JProgressBarDemo
 * @date Date : 2019年11月24日 21:37
 */
public class JProgressBarDemo extends JFrame {

    public JProgressBarDemo(){
        setTitle("使用进度条");
        JLabel label = new JLabel("欢迎使用在线升级功能!");

        JProgressBar progressBar = new JProgressBar();
        JButton button = new JButton("完成");
        button.setEnabled(false);
        Container container = getContentPane();
        container.setLayout(new GridLayout(3,1));
        JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        panel1.add(label);
        panel2.add(progressBar);
        panel3.add(button);
        container.add(panel1);
        container.add(panel2);
        container.add(panel3);
        progressBar.setStringPainted(true);
        //设置显示"升级进行中..."
        progressBar.setString("升级进行中...");
        //使用不确定模式
        //progressBar.setIndeterminate(true);
        //开启一个线程进行处理
        new Progress(progressBar,button).start();

        //单击完成按钮结束
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        JProgressBarDemo demo = new JProgressBarDemo();
        demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        demo.setVisible(true);
        demo.setLocation(500,500);
        demo.pack();

    }

    private class Progress extends Thread{
        JProgressBar progressBar;
        JButton button;
        //进度条上的数字
        int[] progressValue = {6,18,27,39,51,66,81,100};
        Progress(JProgressBar progressBar, JButton button){
            this.progressBar = progressBar;
            this.button = button;
        }

        @Override
        public void run() {
            for (int i = 0; i < progressValue.length; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                progressBar.setValue(progressValue[i]);
            }
            progressBar.setIndeterminate(false);
            progressBar.setString("升级完成!");
            button.setEnabled(true);
        }


    }
}
